package com.example.demo.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

@Slf4j
@Service
public class WechatCloudDBService {

    @Value("${wechat.app-id}")
    private String appId;

    @Value("${wechat.app-secret}")
    private String secret;

    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;

    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={secret}";
    private static final String DATABASE_QUERY_URL = "https://api.weixin.qq.com/tcb/databasequery";
    private static final String DATABASE_UPDATE_URL = "https://api.weixin.qq.com/tcb/databaseupdate";

    public WechatCloudDBService(RestTemplate restTemplate, ObjectMapper objectMapper) {
        this.restTemplate = restTemplate;
        this.objectMapper = objectMapper;
    }

    private String getAccessToken() {
        try {
            Map<String, String> params = Map.of(
                    "appid", appId,
                    "secret", secret
            );

            ResponseEntity<ObjectNode> response = restTemplate.getForEntity(
                    ACCESS_TOKEN_URL,
                    ObjectNode.class,
                    params
            );

            if (response.getBody() != null && response.getBody().has("access_token")) {
                return response.getBody().get("access_token").asText();
            } else {
                throw new RuntimeException("Failed to get access token");
            }
        } catch (Exception e) {
            log.error("获取访问令牌失败: {}", e.getMessage(), e);
            throw new RuntimeException("获取访问令牌失败", e);
        }
    }

    public String query(String collection, String whereClause) {
        String query = String.format(
                "db.collection(\"%s\").where(%s).get()",
                collection,
                whereClause
        );

        return executeQuery(query);
    }

    public String executeQuery(String query) {
        try {
            String accessToken = getAccessToken();
            log.info("获取到的 accessToken: {}", accessToken);

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json");

            ObjectNode requestBody = objectMapper.createObjectNode()
                    .put("env", "yugongwulian-5gl6zld9f8354d43")
                    .put("query", query);

            log.info("请求体: {}", requestBody.toString());

            HttpEntity<String> entity = new HttpEntity<>(requestBody.toString(), headers);

            ResponseEntity<ObjectNode> response = restTemplate.exchange(
                    DATABASE_QUERY_URL + "?access_token=" + accessToken,
                    HttpMethod.POST,
                    entity,
                    ObjectNode.class
            );

            log.info("API 响应状态码: {}", response.getStatusCode());
            log.info("API 响应内容: {}", response.getBody());

            if (response.getBody() != null) {
                return response.getBody().toString();
            } else {
                throw new RuntimeException("Query response body is null");
            }
        } catch (Exception e) {
            log.error("执行数据库查询失败: {}", e.getMessage(), e);
            throw new RuntimeException("执行数据库查询失败", e);
        }
    }

    public String executeAdd(String query) {
        try {
            String accessToken = getAccessToken();

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json");

            ObjectNode requestBody = objectMapper.createObjectNode()
                    .put("env", "yugongwulian-5gl6zld9f8354d43")
                    .put("query", query);

            HttpEntity<String> entity = new HttpEntity<>(requestBody.toString(), headers);

            ResponseEntity<ObjectNode> response = restTemplate.exchange(
                    "https://api.weixin.qq.com/tcb/databaseadd" + "?access_token=" + accessToken,
                    HttpMethod.POST,
                    entity,
                    ObjectNode.class
            );

            if (response.getBody() != null) {
                return response.getBody().toString();
            } else {
                throw new RuntimeException("Add response body is null");
            }
        } catch (Exception e) {
            log.error("执行数据库插入失败: {}", e.getMessage(), e);
            throw new RuntimeException("执行数据库插入失败", e);
        }
    }

    public String executeUpdate(String query) {
        try {
            String accessToken = getAccessToken();

            HttpHeaders headers = new HttpHeaders();
            headers.set("Content-Type", "application/json");

            ObjectNode requestBody = objectMapper.createObjectNode()
                    .put("env", "yugongwulian-5gl6zld9f8354d43")
                    .put("query", query);

            HttpEntity<String> entity = new HttpEntity<>(requestBody.toString(), headers);

            ResponseEntity<ObjectNode> response = restTemplate.exchange(
                    DATABASE_UPDATE_URL + "?access_token=" + accessToken,
                    HttpMethod.POST,
                    entity,
                    ObjectNode.class  // 改为 ObjectNode.class
            );

            if (response.getBody() != null) {
                return response.getBody().toString();  // 将 ObjectNode 转换为 JSON 字符串
            } else {
                throw new RuntimeException("Update response body is null");
            }
        } catch (Exception e) {
            log.error("执行数据库更新失败: {}", e.getMessage(), e);
            throw new RuntimeException("执行数据库更新失败", e);
        }
    }
}